


package com.example.helllo;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.time.LocalDate;

public class ExchangeActivity extends AppCompatActivity implements Runnable{
    EditText inpRMB;
    TextView rmb;
    float dollarRate=0.1531f;
    float euroRate=0.1281f;
    float wonRate=171.4194f;
    private  static final String TAG="ConfigActivity";
    Handler handler;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exchange);
        inpRMB =findViewById(R.id.inputRMB);
        rmb=findViewById(R.id.rmb);
        Intent intent= getIntent();
        //读取数据
        SharedPreferences sharedPreferences=getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        dollarRate=sharedPreferences.getFloat("dollar_rate",dollarRate);
        euroRate=sharedPreferences.getFloat("dollar_rate",euroRate);
        wonRate=sharedPreferences.getFloat("dollar_rate",wonRate);
        String updateStr=sharedPreferences.getString("update_str","");
        //获取当前日期
        LocalDate today=LocalDate.now();
        //比较日期
        Log.i(TAG, "onCreate: updateStr=" + updateStr);
        Log.i(TAG, "onCreate: today=" + today);
        if (updateStr.equals(today.toString())){
            Log.i(TAG, "onCreate: 日期相等，不重新获取");
        }else{
            //开启子线程
            Thread t=new Thread(this);
            t.start();
        }

        //创建handler对象
        handler=new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if(msg.what==1){
                    String val=(String)msg.obj;
                    dollarRate= 100f / Float.valueOf(val);
                    //Toast.makeText(ExchangeActivity.this,"数据已更新",Toast.LENGTH_SHORT).show();
                }else if(msg.what==2){
                    String val=(String)msg.obj;
                    euroRate= 100f /Float.valueOf(val);
                }else if(msg.what==3){
                    String val=(String)msg.obj;
                    wonRate= 100f /Float.valueOf(val);
                }

                Log.i(TAG, "handleMessage: msg.what=" + msg.what);
                //保存获取的汇率数据
                SharedPreferences.Editor editor=sharedPreferences.edit();
                editor.putFloat("dollar_rate", dollarRate);
                editor.putFloat("euro_rate", euroRate);
                editor.putFloat("won_rate", wonRate);
                editor.putString("update_str",today.toString());
                editor.apply();
                Log.i(TAG, "handleMessage: 日期已更新"+today);
                super.handleMessage(msg);
            }
        };



    }
    public void click(View btn){
        float r=0.0f;
        if(btn.getId()==R.id.dollar){
            r=dollarRate;
        }else if(btn.getId()==R.id.euro){
            r=euroRate;
        }else {
            r=wonRate;
        }
        //获取
        String str=inpRMB.getText().toString();
        if(str!=null&& str.length()>0){
            float value = Float.valueOf(str);
            float result = value*r;
            rmb.setText("转换后的金额为"+result);
        }else{
            Toast.makeText(this, "请输入金额", Toast.LENGTH_SHORT).show();
        }

    }
    //    public void open(View v){
////        Intent intent =new Intent(Intent.ACTION_DIAL, Uri.parse("tel:17844594990"));
////        startActivity(intent);
//        Intent score =new Intent(this,SecondActivity.class);
//        startActivity(score);
//    }
    public void  openConfig(View btn){
        show();
    }

    private void show() {//将汇率参数传到Config页面
        Intent config=new Intent(this, ConfigActivity2.class);
        config.putExtra("dollar_key",dollarRate);
        config.putExtra("euro_key",euroRate);
        config.putExtra("won_key",wonRate);

        Log.i(TAG,"openConfig: dollarRate=" + dollarRate);
        Log.i(TAG,"openConfig: euroRate=" + euroRate);
        Log.i(TAG,"openConfig: wonRate=" + wonRate);
        //打开可返回数据窗口
        startActivityForResult(config,1);//为了带回数据。一个是要打开的对象，
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //requestCode区分谁返回的数据，resultCode区分返回的数据按什么格式拆分
        if(requestCode==1&& resultCode==2){//接收Config传回的数据
            Bundle bundle=data.getExtras();
            dollarRate=bundle.getFloat("dollar_key2",0.1f);
            euroRate=bundle.getFloat("euro_key2",0.1f);
            wonRate=bundle.getFloat("won_key2",0.1f);

            Log.i(TAG,"onActivityResult:dollarRate="+dollarRate);
            Log.i(TAG,"onActivityResult:euroRate="+euroRate);
            Log.i(TAG,"onActivityResult:dollarRate="+wonRate);

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.menu_set){
            show();
        }else if(item.getItemId()==R.id.open_list){
            //打开列表窗口
            Intent list=new Intent(this, FirstListActivity.class);
            startActivity(list);
            //测试数据库
//            RateManager manager =new RateManager(this);
//            RateItem item2 =new RateItem("aaaa","12.34");
//            manager.add(item2);
//            manager.add(new RateItem("bbbb","23.54"));
//            Log.i(TAG, "onOptionsItemSelected: 写入数据");
//            //查询所有数据
//            List<RateItem> testList=manager.listAll();
//            for(RateItem i: testList){
//                Log.i(TAG, "onOptionsItemSelected: 取出数据[id="+i.getId()+"]Name="+i.getCurName()+"Rate="+i.getCurRate());
//            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void run() {

        URL url=null;
//        try {
//            url=new URL("http://www.usd-cny.com/icbc.htm");
//            HttpURLConnection http =(HttpURLConnection) url.openConnection();
//            InputStream in=http.getInputStream();
//            String html =inputStream2String(in);
//            Log.i(TAG,"run:html="+ html);
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        try {
            Document doc = Jsoup.connect("http://www.usd-cny.com/icbc.htm").get();
            Log.i(TAG, "title:"+doc.title());
            Element table= doc.getElementsByTag("table").first();
            Log.i(TAG, "run: table=" +table);
            Elements trs=table.getElementsByTag("tr");
            Log.i(TAG, "run: td=" + trs);

            for (Element tr : trs) {
                Elements tds=tr.getElementsByTag("td");
                if(tds.size()>0){
                    String str=tds.get(0).text();
                    Log.i(TAG, "run: str=" + str );
                    String val=tds.get(4).text();
                    Log.i(TAG, "run: val=" + val );
                    if(str.equals("美元")) {
                        Log.i(TAG, "run: str1=" + str + "=>" + val);
                        Message msg=handler.obtainMessage(1);
                        msg.obj=val;
                        handler.sendMessage(msg);
                    }else if(str.equals("欧元")){
                        Log.i(TAG, "run: str=" + str + "=>" + val);
                        Message msg=handler.obtainMessage(2);
                        msg.obj=val;
                        handler.sendMessage(msg);
                    }else if(str.equals("韩币")){
                        Log.i(TAG, "run: str=" + str + "=>" + val);
                        Message msg=handler.obtainMessage(3);
                        msg.obj=val;
                        handler.sendMessage(msg);
                    }
                }
            }
//            for(int i=1;i<=21;i++){
//                Element tr=table.getElementsByTag("tr").get(i);
//                Element td=tr.getElementsByTag("td").get(3);
//                Log.i(TAG, "run: td=" + td);
//            }
//            Element trs=table.getElementsByTag("tr").get(3);
//            Element tr1=trs.getElementsByTag("td").get(3);
//        for (Element tr : trs) {
//            for(Element td:tr.getElementsByTag("td")) {
//                Log.i(TAG, "run: td=" + tr);
//            }
//        }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        Message msg = handler.obtainMessage(5);
//        msg.obj = bund1;
//        handler.sendMessage(msg);



        //返回消息到主线程
//        Message msg=handler.obtainMessage(7);
//        //msg.what=5;
//        msg.obj="Hello from ren()";
//        handler.sendMessage(msg);
    }

    private String inputStream2String(InputStream inputStream) throws IOException {
        final int bufferSize=1024;
        final char[] buffer=new char[bufferSize];
        final StringBuilder out=new StringBuilder();
        Reader in = new InputStreamReader(inputStream,"gb2312");
        while(true){
            int rsz=in.read(buffer,0,buffer.length);
            if(rsz<0)
                break;
            out.append(buffer,0,rsz);
        }
        return out.toString();
    }
}

